<?php
/**
 * User: Hufeng
 * Date: 2017/12/04 17:51
 * Desc: TRADE 任务队列
 */
namespace App\Controller;
use App\Model\StockModel;
use App\Model\TradeDealhistoryModel;
use App\Model\TradeDelegateHistoryModel;
use App\Model\TradeKlineModel;
use App\Model\StockHandicapModel;
use App\Model\TradePlaceModel;
use App\Common\Util\Redis;
use App\Common\Util\WsClient;

class Task {
    //创建任务
    public function build(){
        $taskJson = $_POST['task'];
        $taskObj = json_decode($taskJson,true);
        if($taskObj['taskName'] == 'reqUrl'){
            $this->reqUrl($taskObj['reqUrl'],$taskObj['param']);
            return true;
        }elseif($taskObj['taskName'] == 'tradeData'){
            $this->tradeData($taskObj['param']);
            return true;
        }else{
            return true;
        }
    }
    //短信发送
    protected function sendSms($param){
        return;
    }
    //请求url接口
    protected function reqUrl($url,$param){
        $res = $this->httpCurl($url,$param);
        return $res;
    }
    //交易大盘K线图(分时，日K,周K,月K,年K)，盘口，综合指数数据处理，推送数据（五档数据）
    public function tradeData($param){
        $dateMin = date('Y-m-d H:i');
        $sdateMin = $dateMin.':00';
        $edateMin = $dateMin.':59';
        $tkModel = new TradeKlineModel();
        $shModel = new StockHandicapModel();
        $tdhModel = new TradeDealhistoryModel();
        $tdgModel = new TradeDelegateHistoryModel();
        $sModel = new StockModel();
        $tpModel = new TradePlaceModel();
        $dateNow = date('Y-m-d H:i:s');

        if($param['dealNum'] > 0){
            //分时(股票)
            $tkModel->dealKline($sdateMin,$edateMin,KLINE_TYPE_MIN,1,$dateNow,$param);
            //日K
            $date = date('Y-m-d');
            $sdate = $date.' 00:00:00';
            $edate = $date.' 23:59:59';
            $tkModel->dealKline($sdate,$edate,KLINE_TYPE_DATEK,1,$dateNow,$param);
            //周
            $date=new \DateTime();
            $date->modify('this week');
            $sweek=$date->format('Y-m-d').' 00:00:00';
            $date->modify('this week +6 days');
            $eweek=$date->format('Y-m-d').' 23:59:59';
            $tkModel->dealKline($sweek,$eweek,KLINE_TYPE_WEEKK,1,$dateNow,$param);
            //月
            $smonth = date("Y-m").'-01 00:00:00';
            $emonth = date('Y-m-d', strtotime("$smonth +1 month -1 day")).' 23:59:59';
            $tkModel->dealKline($smonth,$emonth,KLINE_TYPE_MONK,1,$dateNow,$param);
            //年
            $syear = date("Y").'-01-01 00:00:00';
            $eyear = date('Y-m-d', strtotime("$syear +1 year -1 day")).' 23:59:59';
            $tkModel->dealKline($syear,$eyear,KLINE_TYPE_YEARK,1,$dateNow,$param);
        }

        //更新盘口数据
        //股票信息
        $sRes = $sModel->findData(['id'=>$param['sid']]);
        $yclosePrice = $tdhModel->yclosePrice($param['sid']);
        $shRes = $shModel->findData(['sid'=>$param['sid']]);
        if(!$shRes['update_time'] || (strtotime(date('Y-m-d'))>strtotime($shRes['update_time']))){
            $shRes['today_total_price'] = 0;
            $shRes['today_deal_num'] = 0;
            $shRes['today_total_num'] = 0;
            $shRes['low_price'] = 0;
            $shRes['high_price'] = 0;
            $shRes['in_handicap'] = 0;
            $shRes['out_handicap'] = 0;
            if($param['dealNum'] > 0){
                $shData['open_price'] = $param['odealPrice'];
            }
        }
        if($param['dealNum'] > 0) {
            $shData['new_price'] = $param['dealPrice'];
            $todayDealNum = $shRes['today_deal_num'] + $param['dealNum'];
            $todayTotalPrice = $shRes['today_total_price'] + ($param['dealNum'] * $param['dealAvgPrice']);
            $shData['avg_price'] = round($todayTotalPrice / $todayDealNum, 2);
            $shData['today_deal_num'] = $todayDealNum;
            $shData['today_total_price'] = $todayTotalPrice;
            $shData['today_total_num'] = $shRes['today_total_num'] + 1;
            $shData['low_price'] = $shRes['low_price'];
            if ($shRes['low_price'] == 0 || ($shRes['low_price'] > $param['minPrice'])) {
                $shData['low_price'] = $param['minPrice'];
            }
            $shData['high_price'] = $shRes['high_price'];
            if ($shRes['high_price'] == 0 || ($param['maxPrice'] > $shRes['high_price'])) {
                $shData['high_price'] = $param['maxPrice'];
            }
            $shData['rang'] = round(($shData['high_price'] - $shData['low_price']) / $yclosePrice * 100, 2);

            $shData['in_handicap'] = $shRes['in_handicap'] + $param['npNum'];
            $shData['out_handicap'] = $shRes['out_handicap'] + $param['wpNum'];

            $tbMin = $tpModel->tradeBeginMin($sRes['tpid']);
            $shData['volume_ratio'] = round($shData['today_total_num']/$tbMin,2);
            $shData['zd_rang'] = round(($shData['new_price']-$yclosePrice)/$yclosePrice*100,2);
            $shData['change_percent'] = round($todayDealNum/$shRes['stock_num']*100,2);
            $shData['update_time'] = $dateNow;
        }
        //今日委托买入数量
        $tbTotal = $tdgModel->sumData(['sid'=>$param['sid'],'type'=>TRADE_BUY,'addtime[>=]'=>$sdateMin,'addtime[<=]'=>$edateMin],['delegate_num']);
        //今日委托卖出数量
        $tsTotal = $tdgModel->sumData(['sid'=>$param['sid'],'type'=>TRADE_SALE,'addtime[>=]'=>$sdateMin,'addtime[<=]'=>$edateMin],['delegate_num']);
        //今日委托买入手数
        $tbhTotal = $tdgModel->getTotalNum(['sid'=>$param['sid'],'type'=>TRADE_BUY,'addtime[>=]'=>$sdateMin,'addtime[<=]'=>$edateMin]);
        //今日委托卖出手数
        $tshTotal = $tdgModel->getTotalNum(['sid'=>$param['sid'],'type'=>TRADE_SALE,'addtime[>=]'=>$sdateMin,'addtime[<=]'=>$edateMin]);
        $shData['delegate_percent'] = round(($tbhTotal-$tshTotal)/($tbhTotal+$tshTotal)*100,2);
        $shData['delegate_gap'] = $tbTotal-$tsTotal;
        $shModel->editData(['sid'=>$param['sid']],$shData);

        //记录综合指数
        $compQuota = $shModel->compQuota($sRes['tpid']);
        $cparam = $param;
        $cparam['sid'] = $sRes['tpid'];
        $cparam['dealPrice'] = $compQuota;
        $tkModel->dealKline($sdateMin,$edateMin,KLINE_TYPE_MIN,2,$dateNow,$cparam);

        //推送数据(五档数据)
        $this->sendFiveTradeData($param['sid']);
        //推送分时数据
        if($param['dealNum'] > 0) {
            $this->sendTradLineData($param['sid'],$dateNow, $param['dealPrice']);
        }
        return;
    }
    //推送五档数据
    public function sendFiveTradeData($sid){
        $redis = new Redis();
        $saleList = $redis->client->zrange(USER_STOCK_SALE.$sid,0,4,['withscores'=>true]);
        $buyList = $redis->client->zrevrange(USER_STOCK_BUY.$sid,0,4,['withscores'=>true]);
        $saleRes = $buyRes = [];
        $i = 1;
        foreach ($saleList as $key=>$val){
            $priceJson = $redis->client->get(USER_STOCK_SALE_PRIICE.$sid.'_'.$key);
            $priceArr = json_decode($priceJson,true);
            $num = 0;
            foreach ($priceArr as $darr){
                $num += $darr['dnum'];
            }

            $arr = [];
            $arr['name'] = '卖'.$i;
            $arr['price'] = $key;
            $arr['num'] = $num;
            $i++;
            $saleRes[] = $arr;
        }
        for($i;$i<6;$i++){
            $arr = [];
            $arr['name'] = '卖'.$i;
            $arr['price'] = '--';
            $arr['num'] = '--';
            $saleRes[] = $arr;
        }
        $i = 1;
        foreach ($buyList as $key=>$val){
            $priceJson = $redis->client->get(USER_STOCK_BUY_PRIICE.$sid.'_'.$key);
            $priceArr = json_decode($priceJson,true);
            $num = 0;
            foreach ($priceArr as $darr){
                $num += $darr['dnum'];
            }

            $arr = [];
            $arr['name'] = '买'.$i;
            $arr['price'] = $key;
            $arr['num'] = $num;
            $i++;
            $buyRes[] = $arr;
        }
        for($i;$i<6;$i++){
            $arr = [];
            $arr['name'] = '买'.$i;
            $arr['price'] = '--';
            $arr['num'] = '--';
            $buyRes[] = $arr;
        }
        $sendData['buy'] = $buyRes;
        $sendData['sale'] = $saleRes;
        $wsc = new WsClient();
        $wsc->send($sendData,'fiveTradeData-'.$sid);
        return;
    }
    //推送分时数据
    public function sendTradLineData($sid,$time,$price){
        $sendData['time'] = date('H:i',strtotime($time));
        $sendData['price'] = $price;
        $wsc = new WsClient();
        $wsc->send($sendData,'tradeLine-'.$sid);
        return;
    }

    //http请求
    protected function httpCurl($url,$param){
        $ch = curl_init();  //初始化
        curl_setopt($ch, CURLOPT_URL, $url); //设置url
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //不直接输出,以文件流返回
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //超时
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不需要验证对方的证书
        curl_setopt($ch, CURLOPT_POST, true);   //开启post参数传递
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param); //post数组参数
        $response = curl_exec($ch); //执行,返回header body
        curl_close($ch);//关闭
        return $response;
    }
}
